import Link from 'next/link'
import Repo from  './Repo'
import {request} from '../lib/dealRquest'
import { withRouter } from 'next/router'
import { get, set } from '../lib/repo-basic-cache'

const isServer = typeof  window === 'undefined'
function makeQuery(queryObject) {
  const query = Object.entries(queryObject)
    .reduce((result, entry) => {
      result.push(entry.join('='))
      return result
    }, [])
    .join('&')
  return `?${query}`
}
export  default function (Comp, type = 'index') {
  const WithDetail = ({repoBasic, router, ...rest}) => {
    const query = makeQuery(router.query)
    return (
      <div className="root">
        <div className="repo-basic">
          <Repo repo={repoBasic} />
          <div className="tabs">
            {
              type === 'index' ?
              <span className="tab">Readme</span> :
              (
                <Link href={`/detail${query}`}>
                  <a className="tab index">
                    ReadMe
                  </a>
                </Link>
              )
            }
            {
              type === 'issues' ?
              <span className="tab">issues</span> :
              (
                <Link  href={`/detail/issues${query}`}>
                  <a className="tab issues">
                    Issues
                  </a>
                </Link>
              )
            }
            
          </div>
        </div>
        <div>
          <Comp {...rest}/>
        </div>
        <style jsx>{`
        .root {
          padding-top: 20px;
        }
        .repo-basic {
          padding: 20px;
          border: 1px solid #eeeeee;
          margin-bottom: 20px;
          border-radius: 5px;
        }
        .tab + .tab {
          margin-left: 20px;
        }
      `}</style>
      </div>
    )
  }
  WithDetail.getInitialProps = async (ctx) => {
    const { owner, name } = ctx.query
    const full_name = `${owner}/${name}`
    
    let pageData = {}
    if(Comp.getInitialProps) {
      pageData = await Comp.getInitialProps(ctx)
    }
    
    if(get(full_name)){
      return {
        repoBasic: get(full_name),
        ...pageData
      }
    }
    
    const repoBasic = await request({
      url: `/repos/${owner}/${name}`
    },ctx.req, ctx.res)
    
     if(!isServer){
       set(repoBasic.data)
     }
    
    return {
      repoBasic: repoBasic.data,
      ...pageData
    }
  }
  return withRouter(WithDetail)
}
